import facade
import pymysql
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")
topPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(topPath, "download", "adks_cqjd", "download", "cover")
BaseDir.create_dir(sPath)


class DownAuthorMsg(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutiles = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.proxys = {
            "http": "192.168.30.176:8171",
            "https": "192.168.30.176:8171"
        }

    def select(self):
        sql = "SELECT DISTINCT rawid,coverurl from article WHERE coverstat=0"
        rows = self.mysqlutiles.SelectFromDB(sql)
        for row in rows:
            name = row[0].lower() + ".jpg"
            filepath = BaseDir.get_new_path(sPath, name)
            if BaseDir.is_file_exists(filepath):
                sql = "update article set coverstat=1 where coverurl='{}'".format(row[1])
                self.mysqlutiles.ExeSqlToDB(sql)
                continue
            url = row[1]
            fullurl = url
            BoolResult, errString, r = facade.BaseRequest(fullurl, timeout=30, endstring="", proxies=self.proxys)

            if BoolResult:
                if row[0].lower == "14227":
                    print("特殊情况")
                    continue
                name = row[0].lower() + ".jpg"
                ImageFile.img_to_format_jpg(r.content, BaseDir.get_new_path(sPath, name))
                sql = "update article set coverstat=1 where coverurl='{}'".format(url)
                self.mysqlutiles.ExeSqlToDB(sql)
            else:
                print("下载失败，请检查")


if __name__ == "__main__":
    down = DownAuthorMsg()
    down.select()
